<style scoped>
	.formButton {
		text-align: right;
		width: 100%;
		border-top: 1px solid var(--divider-color);
		/*margin-top: 120px;*/
		padding-top: 16px;
	}

	.editor {
		height: 300px;
	}

	.editor /deep/ .ql-container {
		height: calc(100% - 82px);
		overflow: auto;
	}
	.users-wrapper{
		border: 1px solid var(--select-border-color);
		border-radius: 5px;
		padding: 4px 10px;
		max-height: 300px;
		overflow: auto;
		overscroll-behavior: contain;
	}
</style>
<style>
	.ql-snow.ql-toolbar button.ql-file{
		font-size: 16px;
		display: inline-block;
	    font-family: Ionicons;
	    font-style: normal;
	    font-weight: 400;
	    font-variant: normal;
	    text-transform: none;
	    text-rendering: optimizeLegibility;
	    line-height: 1;
	    -webkit-font-smoothing: antialiased;
	    -moz-osx-font-smoothing: grayscale;
	    vertical-align: -.125em;
	    text-align: center;
	}
	.ql-snow.ql-toolbar button.ql-file:before {
	    content: "\F255";
	    /*"PDF"*/
	}
</style>
<template>
	<div class="boardcast" style="padding: 10px">
		<Form ref="formValidate" :model="formValidate" :rules="formValidateRule" :label-width="100">
			<FormItem label="类型" prop="receiverType" key="receiverType">
				<RadioGroup v-model="formValidate.receiverType" @on-change="changeReceiverType">
					<Radio :label='1'>实验组</Radio>
					<Radio :label='2'>个人</Radio>
				</RadioGroup>
			</FormItem>
			<div v-if="formValidate.receiverType == 2">
				<FormItem label="用户类型" prop="type" v-if="formValidate.receiverType == 2" key="userType">
					<Select filterable v-model="userType" style="width: 150px" @on-change="getCompanyUsers">
						<!--<Option value="all">{{$t('type')}}</Option>
				        <Option value="leader">{{$t('RootDesigner')}}</Option>
				        <Option value="member">{{$t('OrdinaryDesigner')}} </Option>
				        <Option value="evaluator">{{$t('reviewer')}} </Option>
				        <Option value="experimenter">{{$t('experimenters')}} </Option>-->
						<Option value="all">全部类型</Option>
						<Option value="leader">单位管理员</Option>
						<Option value="member">单位设计师</Option>
						<!--
                        <Option value="evaluator">评估人员</Option>
                        <Option value="referee">裁判人员</Option>
						-->
						<Option value="experimenter">操作员</Option>
					</Select>
				</FormItem>
				<FormItem label="用户" prop="userIds" key="userIds">
					<Transfer :data="transferCompanyUsers" :list-style="listStyle" :target-keys="formValidate.userIds" :render-format="render2" :filter-method="filterMethod" :operations="['移除','选择']" :titles="['未选用户','已选用户']" filterable @on-change="handleChange"></Transfer>
				</FormItem>
			</div>
			<div v-if="formValidate.receiverType == 1">
				<FormItem label="实验组" prop="accessGroups" key="accessGroups">
					<Select filterable v-model="formValidate.accessGroups" placeholder="选择团队" multiple filterable @on-change="getAccessGroupMember">
						<Option v-for="item in accessGroupList" :value="item.id" :key="item.id" :title="item.name">{{item.name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="成员" prop="accessGroups_copy" key="accessGroups_copy">
					<div :class="{'users-wrapper':formValidate.accessGroups_copy.length > 0 ? true : false}">
						<div v-for="group in formValidate.accessGroups_copy" :key="group.id">
							<!--{{group}}-->
							<div>
								<small style="font-size: 12px;margin-left:2em;">组: </small>
								<Checkbox :value="group.checkAll" @click.prevent.native="handleCheckAll($event,group)" :disabled="group.disabled"> {{group.name}}</Checkbox>
							</div>
							<CheckboxGroup v-model="group.userIds" @on-change="checkAllGroupChange($event,group)">
								<small style="font-size: 12px;">组成员:</small>
								<Checkbox :label="user.userId" v-for="user in group.userList" :key="`${group.id}-${user.userId}`" :disabled="group.disabled">{{user.userName}}</Checkbox>
							</CheckboxGroup>
							<!--</div>-->
						</div>
					</div>
				</FormItem>
			</div>
			<FormItem label="公告类型" prop="type" key="boardType">
				<RadioGroup v-model="formValidate.type">
					<Radio :label=1><span class="sw">事务公告</span></Radio>
					<!--<Radio :label=2>普通公告</Radio>-->
					<Radio :label=3><span class="wg">违规公告</span></Radio>
					<!--<Radio :label=4>系统公告</Radio>-->
				</RadioGroup>
			</FormItem>
			<FormItem label="内容" prop="content" key="content">
				<!--<Input v-model.trim="formValidate.content" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容"></Input>-->
				<quill-editor v-model="formValidate.content" class="editor" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)">
				</quill-editor>
				<div style="text-align:right;">
					{{tiLength}}/500
				</div>
				<span style="color:#f90"> <Icon type="ios-information-circle-outline" />仅允许粘贴文本内容，粘贴内容中的图片、链接和样式将无效</span>
				<Upload ref="upload" style="display:inline-block" :show-upload-list="false" :on-success="handleSuccess" 
					:on-format-error="handleFormatErrorImg" :format="['jpg','jpeg','png','gif']"  multiple :action="uploadUrl">
					<Button icon="ios-cloud-upload-outline" id="imgUploadBtn" v-show="false"></Button>
				</Upload>
				<Upload ref="fileUpload" style="display:inline-block" :show-upload-list="false" :on-success="handleFileSuccess" 
					:on-format-error="handleFormatErrorFile" :format="['pdf']"  multiple :action="fileUploadUrl">
					<Button icon="ios-cloud-upload-outline" id="fileUploadBtn" v-show="false"></Button>
				</Upload>
			</FormItem>
			<FormItem class="formButton">
				<Button @click="cancel('formValidate')">取消</Button>
				<Button type="primary" @click="sendToUserGroup()" :loading="disabledSend" style="margin-left: 8px" v-if="formValidate.receiverType == 1">发送</Button>
				<Button type="primary" @click="sendToUser()" :loading="disabledSend" style="margin-left: 8px" v-if="formValidate.receiverType == 2">发送</Button>
			</FormItem>
		</Form>
	</div>
</template>
<script>
	//import Cookies from 'js-cookie';
	//import encryption from '@/libs/encryption.js'
	import {
		quillEditor
	} from "vue-quill-editor"; // 调用编辑器
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'
	import 'quill/dist/quill.bubble.css'
	//引入Qill插件
	import Quill from "quill";
	let Link = Quill.import("formats/link");
	// 自定义a链接
	class FileBlot extends Link {
		// 继承Link Blot
		static create(value) {
			let node = undefined;
			if(value && !value.href) {
				// 适应原本的Link Blot
				node = super.create(value);
			} else {
				// 自定义Link Blot
				node = super.create(value.href);
				node.innerText = value.innerText;
				node.href = value.href;
				node.id = value.id;
				node.setAttribute("title", '点击可下载:'+value.innerText);
				node.setAttribute("data-value", value.dataValue);
			}
			return node;
		}
	}
	FileBlot.blotName = "link";
	FileBlot.tagName = "A";
	//注册FileBlot
	Quill.register(FileBlot);
	import {
		sendToUser,
		sendToUserGroup
	} from '@/api/boardcast_new.js'
	import {
		queryCompanyUsers,
		queryExperGroups,
		getExperGroupsUsers
	} from '@/api/users.js'
	const toolbarOptions = [
		["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
		//  ["blockquote", "code-block"], // 引用  代码块
		[{header: 1}, {header: 2}], // 1、2 级标题
		//  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
		[{script: "sub"}, {script: "super"}], // 上标/下标
		[{indent: "-1"}, {indent: "+1"}], // 缩进
		//  [{'direction': 'rtl'}],// 文本方向
		[{size: ["small", false, "large", "huge"]}], // 字体大小
		[{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
		[{color: []}, {background: []}], // 字体颜色、字体背景颜色
		//  [{ font: [] }], // 字体种类
		[{align: []}], // 对齐方式
		["clean"], // 清除文本格式
		["image"], // 链接、图片、视频
		["file"], // pdf
	];
	export default {
		components: {
			quillEditor,
		},
		data() {
			const validateGroupUserNum = (rule, value, callback) => { //验证只能填入数字		         
				//验证警戒值		    
				if(value.length > 0) {
					value.forEach(group => {
						if(group.userIds.length == 0) {
							callback(new Error('每组请至少选择一个用户'));
						} else {
							callback()
						}
					})
				} else {
					callback()
				}
			}
//			let September = sessionStorage.getItem('November')
//			September = JSON.parse(encryption.SelfUseDecrypt(September));
//			console.log(September)
			return {
//				USER_ID: September.userId,
//				USER_Name: September.nickname,
//				isRootDesigner: September.isRootDesigner,
				accessGroupList: [],
				tiLength: 0,
				formValidate: {
					//"sencensType":"",
					"receiverType": 1,
					//"sceneId":this.$route.query.id,
					"accessGroups": [],
					"accessGroups_copy": [],
					"content": "",
					"id": "",
					"title": "",
					"type": 1,
					"userIds": [],
				},
				accessGroups_copy: [],
				formValidateRule: {
					sceneId: [{
						required: true,
						message: '请选择场景',
						trigger: 'change'
					}],
					type: [{
						required: true,
						type: 'number',
						message: '请选择场景类型',
						trigger: 'change'
					}],
					receiverType: [{
						required: true,
						type: 'number',
						message: '不能为空',
						trigger: 'change'
					}],
					accessGroups: [{
						required: true,
						type: "array",
						min: 1,
						message: '不能为空',
						trigger: 'change'
					}],
					"accessGroups_copy": [{
						required: true,
						type: "array",
						min: 1,
						message: '不能为空',
						trigger: 'change'
					}, {
						validator: validateGroupUserNum,
						trigger: 'change'
					}],
					content: [{
						required: true,
						message: '请输入内容',
						trigger: 'change'
					}],
					userIds: [{
						required: true,
						type: "array",
						min: 1,
						message: '不能为空',
						trigger: 'change'
					}, ]
				},
				companyUsers: [],
				transferCompanyUsers: [],
				listStyle: {
					width: '240px',
					height: '300px'
				},
				editorOption: {
					modules: {
						clipboard: {
							// 粘贴版，处理粘贴时候带图片
							matchers: [
								[Node.ELEMENT_NODE, this.handleCustomMatcher]
							],
						},
						toolbar: {
							container: toolbarOptions, //工具菜单栏配置
							handlers: {
								'image': (value) => {
									if(value) {
										//this.insertImg()
										document.querySelector('#imgUploadBtn').click()
									} else {
										this.quill.format('image', false);
									}
								},
								'file': (value) => {
									if(value) {
										document.querySelector('#fileUploadBtn').click()
									}
								}
							}
						},
					},
					placeholder: '请输入内容',//this.$t('content'), //提示
				},
				uploadUrl: '',
				fileUploadUrl: '',
				setUpLoadHead: {
					'Authorization': localStorage.getItem('token')
				},
				userType: 'all',
				disabledSend: false
			}
		},
		computed: {
			editor() {
				return this.$refs.myQuillEditor.quill;
			},
		},
		mounted() {
			this.uploadUrl = `/api/minio/upload/permanent?visibility=company&type=images&bucket=images`;
			this.fileUploadUrl = `/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs`;
			this.getGroupList(); //接入组
			this.getCompanyUsers(); //单位人员
			//发送文件图标添加title
			let fileUplodEle = document.querySelector('.ql-formats .ql-file');
			fileUplodEle.setAttribute("title", '上传pdf文件');
		},
		methods: {
			//发送图片
			handleSuccess(res) {
				if(res.code == 1) {
					// 获取光标所在位置
					let quill = this.$refs.myQuillEditor.quill
					let length = quill.getSelection().index;
					// 插入图片，res为服务器返回的图片链接地址
					let url = `/Learn/${res.data}`
					quill.insertEmbed(length, 'image', url);
				} else {
					this.$Message.error(data.message);
				}
			},
			//发送文件
			handleFileSuccess(res) {
				if(res.code == 1) {
					// 获取光标所在位置
					let quill = this.$refs.myQuillEditor.quill
					let length = quill.getSelection().index || 1;
					// 插入图片，res为服务器返回的图片链接地址
					let url = `${this.baseURL}/minio/download?path=${res.data}`; //`/Learn/${res.data}`
					quill.insertEmbed(length, 'text', "[");
					quill.insertEmbed(length+1, 'link', {
						href: url,
						innerText: res.info.originalName,
						id:res.info.id,
						dataValue:`/Learn/${res.data}`
					}, "api");
					quill.insertEmbed(length+res.info.originalName.length +1, 'text', "]");
				} else {
					this.$Message.error(data.message);
				}
			},
			handleFormatErrorImg(){
				this.$Message.warning('仅允许上传pdf,jpg,png,gif格式文件');
			},
			handleFormatErrorFile(){
				this.$Message.warning('仅允许上传pdf格式文件');
			},
			getGroupList() {
				//				if(!testId){
				//					return;
				//				}
				let params = {
					pageIndex: 1,
					pageSize: 10000,
					order: 'desc',
					sortBy: 'created'
				};
				queryExperGroups(params).then(data => {
					if(data.code == 1) {
						this.accessGroupList = data.data.items.filter(group => group.userCount > 0);
						this.formValidate.accessGroups = [];
						this.formValidate.accessGroups_copy = [];
					} else if(data.code == -2) {
						this.accessGroupList = [];
					} else {
						this.$Message.error(data.message);
					}
				})
			},
			getAccessGroupMember(ids) {
				this.formValidate.accessGroups_copy = [];
				ids.forEach(id => {
					let group = this.accessGroupList.filter(group => group.id == id)[0];
					if(!group.userList) {
						getExperGroupsUsers(id).then(data => {
							if(data.code == 1) {
								group.checkAll = false;
								this.$set(group, 'checkAll', true);
								this.$set(group, 'disabled', false);
								this.$set(group, 'groupId', group.id);
								this.$set(group, 'userList', data.data);
								this.$set(group, 'userIds', data.data.map(user => user.userId));
								this.formValidate.accessGroups_copy.push(group);
							} else {
								this.$Message.error(data.message);
								this.formValidate.accessGroups_copy.push(group);
							}
						}).catch(error => {
							console.log(error)
							this.formValidate.accessGroups_copy.push(group);
						})
					} else {
						this.formValidate.accessGroups_copy.push(group);
					}
				})
			},
			handleCheckAll(status, group) {
				group.checkAll = !group.checkAll;
				//group.checkAll = true;
				//this.$set(group,'checkAll',!group.checkAll);
				if(group.checkAll) {
					//curGroup.userIds = group.userList.map(user => user.userId);
					group.userIds = group.userList.map(user => user.userId);
				} else {
					group.userIds = [];
				}
			},
			checkAllGroupChange(data, group) {
				if(data.length === group.userList.length) {
					//                  this.formValidate.indeterminate = false;
					group.checkAll = true;
				} else if(data.length > 0) {
					//this.formValidate.indeterminate = true;
					group.checkAll = false;
				} else {
					//this.formValidate.indeterminate = false;
					group.checkAll = false;
				}
			},
			typeFilter(type) {
				let types = '';
				if(type == 1) {
					types = '事务公告'
				}
				// else if (type == 2) {
				// 	types = '普通公告'
				// }
				else if(type == 3) {
					types = '违规公告'
				}
				// else if (type == 4) {
				// 	types = '系统公告'
				// }
				return types;
			},
			sendToUser() {
				this.disabledSend = true;
				let userType = '';
				if(this.formValidate.type == 'leader' || this.formValidate.type == 'member' || this.formValidate.type == 'evaluator') {
					userType = 'designer';
				} else {
					userType = 'experimenter';
				}
				this.$refs.formValidate.validate((valid) => {
					if(valid) {
						let params = {
							"content": this.formValidate.content,
							"id": "",
							"status": 0,
							"title": "",
							"type": this.formValidate.type,
							"users": [{
								"userIds": this.formValidate.userIds,
								//							      "userType": userType
							}]
						}
						sendToUser(params).then(data => {
							if(data.code == 1) {
								this.$Message.info('发送成功');
								this.$emit('hideModal');
							} else {
								this.$Message.error(data.message);
							}
							this.disabledSend = false;
						}).catch(error => {
							this.$Message.error("公告发送失败");
							this.disabledSend = false;
						})
					} else {
						this.disabledSend = false;
					}
				})
			},
			sendToUserGroup() {
				this.disabledSend = true;
				this.$refs.formValidate.validate((valid) => {
					if(valid) {
						let userIds = [];
						let params = {
							users:this.formValidate.accessGroups_copy.map((group,index) => {
								let filtersUserIds = [];
								if(index > 0){
									filtersUserIds = group.userIds.filter(userId => !userIds.includes(userId))
								}else{
									filtersUserIds = group.userIds;
								}
								userIds = userIds.concat(group.userIds);
							  	return {
							  	  	userGroupType: 1,
							  	  	groupId:group.groupId,
							  	  	userIds:filtersUserIds
							  	}
							}).filter(item => item.userIds.length > 0),
							"content": this.formValidate.content,
							"id": this.formValidate.id,
							"title": this.formValidate.title,
							"type": this.formValidate.type
						}
						sendToUserGroup(params).then(data => {
							if(data.code == 1) {
								this.$Message.info('发送成功');
								this.$emit('hideModal');
							} else {
								this.$Message.error(data.message);
							}
							this.disabledSend = false;
						}).catch(error => {
							this.$Message.error("公告发送失败");
							this.disabledSend = false;
						})
					} else {
						this.disabledSend = false;
					}
				})
			},
			cancel(name) {
				this.$refs[name].resetFields();
				this.$emit('hideModal');
			},
			onEditorBlur() {}, // 失去焦点事件
			onEditorFocus() {}, // 获得焦点事件
			onEditorChange(event) {
				if(this.formValidate.content===''){
					this.tiLength = 0
				}
				else{
					this.tiLength = event.quill.getLength()-1
				}
				if (this.tiLength > 500) {
					event.quill.deleteText(500, this.tiLength - 500);
				}
			}, // 内容改变事件
			getCompanyUsers(type) {
				let params = {
					pageIndex: 1,
					pageSize: 2147483646,
					type: type,
					order: 'desc',
					sortBy: 'created',
					type: type
				};
				if(type == 'leader' || type == 'member' || type == 'evaluator' || type == "referee") {
					params.type = 'designer';
					params.role = type;
				} else if(type == 'all') {
					delete params.type;
				}
				//		     	this.formValidateUser.receiverType =  type;
				queryCompanyUsers(params).then(data => {
					if(data.code == 1) {
						this.companyUsers = data.data.items;
						this.transferCompanyUsers = data.data.items.map(user => {
							return {
								key: user.id,
								label: user.username,
								nickname: user.nickname
							}
						})
					} else {

					}
				})
			},
			filterMethod(data, query) {
				//return data.label.indexOf(query) > -1 || data.des.indexOf(query) > -1;
				return data.label.indexOf(query.trim()) > -1
			},
			handleChange(targetKeys, direction, moveKeys) {
				this.formValidate.userIds = targetKeys;
			},
			render2(user) {
				return user.label + '<span style="float:right">' + user.nickname + '</span>'
			},
			changeReceiverType(type) {
				if(type == 2) {
					this.formValidate.accessGroups = [];
					this.formValidate.accessGroups_copy = [];
					this.formValidate.content = '';
				} else {
					this.formValidate.userIds = [];
					this.formValidate.content = '';
					//		    		this.formValidate.accessGroups_copy.forEach(group => {
					//		    			group.disabled = true;
					//		    			group.checkAll = true;
					//		    			group.userIds = group.userList.map(user => user.userId);
					//		    		})
				}
			},
			handleCustomMatcher(node, Delta) {
				let ops = []
				Delta.ops.forEach(op => {
					if(op.insert && typeof op.insert === 'string') { // 如果粘贴了图片，这里会是一个对象，所以可以这样处理
						ops.push({
							insert: op.insert,
						})
					}
				})
				Delta.ops = ops
				return Delta
			}
		}
	}
</script>